import React, { useState, useEffect } from 'react';
import { Button, Table, Input, DatePicker } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

const { Search } = Input;

const BorrowBookList = () => {
    const navigate = useNavigate();
    // 模拟借阅数据，包含借阅时间、是否逾期和库存
    const [borrowData, setBorrowData] = useState(() => {
        return Array.from({ length: 100 }, (_, index) => {
            const borrowDate = new Date();
            borrowDate.setDate(borrowDate.getDate() - Math.floor(Math.random() * 30));
            const isOverdue = Math.random() > 0.5;
            // 随机生成库存数量
            const stock = Math.floor(Math.random() * 100);
            const borrower = `借阅者${index + 1}`; // 假设每个借阅者都有一个唯一的ID或名称，这里用索引代替，你可以根据实际情况替换为实际的borrower objec
            return {
                key: index,
                id: index + 1,
                bookName: `书籍${index + 1}`,
                borrowDate: borrowDate.toISOString().split('T')[0],
                isOverdue,
                stock,
                borrower
            };
        });
    });

    // 存储筛选后的数据
    const [filteredData, setFilteredData] = useState(borrowData);
    // 筛选状态
    const [filterStatus, setFilterStatus] = useState(null);
    // 新增选中状态
    const [selectedButton, setSelectedButton] = useState(null);

    // 按借阅时间从近到远排序
    useEffect(() => {
        const sortedData = [...borrowData].sort((a, b) => {
            return new Date(b.borrowDate) - new Date(a.borrowDate);
        });
        setFilteredData(sortedData);
    }, [borrowData]);

    // 筛选函数
    const handleFilter = (status) => {
        if (filterStatus === status) {
            // 再次点击所选按键，取消筛选
            setFilteredData(borrowData);
            setFilterStatus(null);
            setSelectedButton(null);
        } else {
            const newFilteredData = borrowData.filter(item => {
                if (status === 'overdue') {
                    return item.isOverdue;
                } else {
                    return !item.isOverdue;
                }
            });
            setFilteredData(newFilteredData);
            setFilterStatus(status);
            setSelectedButton(status);
        }
    };

    const columns = [
        { title: 'ID', dataIndex: 'id', key: 'id' },
        { 
            title: '书名', 
            dataIndex: 'bookName', 
            key: 'bookName',
            render: (text, record) => (
                <span onClick={() => navigate(`/book/${record.id}`)} style={{ cursor: 'pointer'}}>
                    {text}
                </span>
            ),
            // 添加搜索框
            filters: [],
            onFilter: (value, record) => record.bookName.toLowerCase().includes(value.toLowerCase()),
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div style={{ padding: 8 }}>
                    <Search
                        placeholder="按书名搜索"
                        value={selectedKeys[0]}
                        onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={() => confirm()} 
                        style={{ width: 188, marginBottom: 8, display: 'block' }}
                    />
                    <Button
                        onClick={() => confirm()}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{ width: 90, marginRight: 8 }}
                    >
                        筛选
                    </Button>
                    <Button onClick={() => clearFilters()} size="small" style={{ width: 90 }}>
                        重置
                    </Button>
                </div>
            ),
        },
        { 
            title: '借阅时间', 
            dataIndex: 'borrowDate', 
            key: 'borrowDate',
            filters: [],
            onFilter: (value, record) => {
                const itemDate = new Date(record.borrowDate);
                const filterDate = new Date(value);
                return itemDate.toDateString() === filterDate.toDateString();
            },
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div style={{ padding: 8 }}>
                    <DatePicker
                        value={selectedKeys[0] ?  dayjs(selectedKeys[0]) : null}
                        onChange={(date) => {
                            if (date) {
                                setSelectedKeys([date.format('YYYY-MM-DD')]);
                            } else {
                                setSelectedKeys([]);
                            }
                        }}
                        style={{ width: 188, marginBottom: 8, display: 'block' }}
                    />
                    <Button
                        onClick={() => confirm()}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{ width: 90, marginRight: 8 }}
                    >
                        筛选
                    </Button>
                    <Button onClick={() => clearFilters()} size="small" style={{ width: 90 }}>
                        重置
                    </Button>
                </div>
            ),
        },
        { title: '是否逾期', dataIndex: 'isOverdue', key: 'isOverdue', render: (isOverdue) => isOverdue ? '逾期' : '未逾期' },
        // 添加库存列
        { title: '库存', dataIndex: 'stock', key: 'stock' },
         // 添加借阅者列
         { title: '借阅者', dataIndex: 'borrower', key: 'borrower' },
    ]; 

    // 定义选中样式
    const selectedStyle = {
        backgroundColor: '#1890ff',
        color: 'white',
    };

    return ( 
        <div>
            <div className="filter-buttons">
                <Button
                    onClick={() => handleFilter('notOverdue')}
                    style={selectedButton === 'notOverdue' ? selectedStyle : {}}
                >未逾期</Button>
                <Button
                    onClick={() => handleFilter('overdue')}
                    style={selectedButton === 'overdue' ? selectedStyle : {}}
                >逾期</Button>
            </div>
            <Table columns={columns} dataSource={filteredData} />
        </div>
    );
};

export default BorrowBookList;